Heap Memory and Stack Memory
(Tap the post to see more)
In Java, memory management is a vital process.
It is managed by Java automatically.
The JVM divides the memory into two parts: stack memory and heap memory.
From the perspective of Java, both are important memory areas but both are used for different purposes.
The major difference between Stack memory and heap memory is that the stack is used to store the order of method execution and local variables while the heap memory stores the objects and it uses dynamic memory allocation and deallocation.
|
Parameter |
Stack Memory |
Heap Space |
|
Application |
It
stores items that have a very short life such as methods, variables, and reference
variables of the objects. |
It
stores objects and Java Runtime
Environment (JRE) classes. |
|
Ordering |
It
follows the LIFO order. |
It does
not follow any order because it is a dynamic memory allocation and does not
have any fixed pattern for allocation and deallocation of memory blocks. |
|
Flexibility |
It
is not flexible because we cannot
alter the allocated memory. |
It
is flexible because we can alter
the allocated memory. |
|
Efficiency |
It
has faster access, allocation, and
deallocation. |
It
has slower access, allocation, and
deallocation. |
|
Memory Size |
It
is smaller in size. |
It
is larger in size. |
|
Java Options Used |
We
can increase the stack size by using the JVM option -Xss. |
We
can increase or decrease the heap memory size by using the -Xmx
and -Xms JVM options. |
|
Visibility or Scope |
The
variables are visible only to the owner thread. |
It
is visible to all threads. |
|
Generation of Space |
When
a thread is created, the operating system automatically allocates the stack. |
To
create the heap space for the application, the language first calls the
operating system at run time. |
|
Distribution |
Separate
stack is created for each object. |
It
is shared among all the threads. |
|
Exception Throws |
JVM
throws the java.lang.StackOverFlowError
if the stack size is greater than the limit. To avoid this error, increase
the stack size. |
JVM
throws the java.lang.OutOfMemoryError
if the JVM is unable to create a new native method. |
|
Allocation/ Deallocation |
It
is done automatically by the compiler. |
It
is done manually by the programmer. |
|
Cost |
Its
cost is less. |
Its
cost is more in comparison to
stack. |
|
Implementation |
Its
implementation is hard. |
Its
implementation is easy. |
|
Order of allocation |
Memory
allocation is continuous. |
Memory
allocated in random order. |
|
Thread-Safety |
It
is thread-safe because each thread has its own stack. |
It
is not thread-safe, so properly synchronization of code is required. |


Comments